﻿    //查询表单
    	 $('#searchForm').form().show();
	// 请求服务器获取数据的方法
	var getPerData = function(page, rowNum, sortname, sortorder) { // 请求服务器获取数据的方法
    	$("#plan_jqGrid").jqGrid("getGridParam","rowNum");
    	$("#plan_jqGrid").jqGrid("setGridParam",{page:page});
    	rowNum = rowNum || $("#plan_jqGrid").jqGrid("getGridParam","rowNum");
        page = $("#plan_jqGrid").jqGrid("getGridParam","page");
        start = (page-1)*rowNum;
        start = start<0?0:start;
        
        var queryParam =  $('#searchForm').form('value');//序列化表格内容为字符串
        queryParam.nodeId = $('input[name="nodeId"]').attr("vId");
        queryParam.dbLinkId = $('input[name="dbLinkId"]').attr("vId");
        fish.extend(queryParam,{page: JSON.stringify($("#plan_jqGrid").jqGrid("getGridParam","page")),
                limit : rowNum,
                start : start});
        $.ajax({
            url: webRoot+'baseconfig/dmplan/queryRecordByPageDraft.do',
//            url: webRoot+'baseconfig/dmsrctable/queryDmPlanId.do',
            async : true,
            type : 'POST',
            data :queryParam
        }).done(function(serverData, textStatus, jqXHR) {
            var data = eval("(" + jqXHR.responseText + ")");
            //jQuery("#user_jqGrid").jqGrid("reloadData",jqXHR.responseText);
            jQuery("#plan_jqGrid").jqGrid("reloadData",data);
            //jQuery("#user_jqGrid").jqGrid("reloadData",serverData);
            return false;
            //return serverData;
            
        }).fail(function() {
            toastr.error("网络连接失败", "失败");
        }).always(function() {
        	$.unblockUI();
        });
        return false;
    };
    //默认加载
    var getPerData2 = function(page, sortname, sortorder) {
	    _.delay(function(){
	        var result = getPerData(page, sortname, sortorder);
	        jQuery("#plan_jqGrid").jqGrid("reloadData",result);
	    }, 100);
	    $.blockUI({message : "数据载入中,请稍候..."});
    	return false;
	};
	    	//悬浮框
//     	function mouseOver(target){
//				var tdW = ($(target).parent().width()+14);
//				$(target).attr('class','glyphicon glyphicon-option-vertical pull-right').nextAll('.dropdown-list').css('width',tdW).slideDown("fast");
//		}
//		function mouseOut(target){
//				$(target).attr('class','glyphicon glyphicon-option-horizontal pull-right').nextAll('.dropdown-list').hide();
//		}	
		function OnclickMore(target){
			var tdW = ($(target).parent().width()+14);
			$('body').bind('mousedown',function HideOnclickMore(e){
				if(!(e.target.className =='dropdown-list' || $(e.target).parents('.dropdown-list').length > 0 || e.target.className =='glyphicon glyphicon-option-vertical pull-right')){
					$(target).attr('class','glyphicon glyphicon-option-horizontal pull-right').nextAll('.dropdown-list').hide();
					$('body').unbind('mousedown',HideOnclickMore);
					return;
				}
			});
			$(target).attr('class', $(target).hasClass('glyphicon-option-vertical') ? 'glyphicon glyphicon-option-horizontal pull-right' : 'glyphicon glyphicon-option-vertical pull-right').nextAll('.dropdown-list').css('width',tdW).slideToggle('fast');
		}
		var cellval_j;
		function formatter(cellval, opts, rwdat, _act,txt){
			//var tpl = '<a href="javascript:void(0)" onmouseover="mouseOver(this)" onmouseout="mouseOut(this)" class="glyphicon glyphicon-option-horizontal pull-right"></a>';
			var tpl = '<a href="javascript:void(0)" onclick="OnclickMore(this)" class="glyphicon glyphicon-option-horizontal pull-right"></a>';
				var queryForm =  $('#searchForm').form('value');
				if(txt=='sourceData'){
					if(queryForm.tableName==""){
						tpl +=cellval[0];
						cellval_j=0;
					}else{
						for(var i=0; i < cellval.length ; i++){
							if(cellval[i].indexOf(queryForm.tableName)>-1){
							tpl +=cellval[i];
							cellval_j=i;
							break;
							}
						}
					}
				}else{
					tpl += cellval[cellval_j];
				}
//				tpl += cellval[0];
				tpl += '<ul class="dropdown-list" style="left:auto;margin:7px 0 0 -7px;top:auto;min-width:10px">';
				for(var i=0; i < cellval.length ; i++){
					tpl += '<li>'+cellval[i]+'</li>';
				}
				tpl += '</ul>';
				return tpl;
		}
	$(document).ready(function() {
	  	$('#dbLinkId').next(".input-group-addon").click(function() {
			$("#dbLinkId").val("");
			$('input[name="dbLinkId"]').attr("vId","");
		});
		$('#nodeId').next(".input-group-addon").click(function() {
			$("#nodeId").val("");
			$('input[name="nodeId"]').attr("vId","");
		});
	  $('#dbUserName').clearinput();
	  $('#planName').clearinput();
	  $('#tableName').clearinput();
	    $('#resetBtn').click(function() {
	       $('input[name="nodeId"]').attr("vId","");	
	       $('input[name="dbLinkId"]').attr("vId","");
    });
// 所属系统，下拉树
	var nodeId_setting = {
		async: {
			enable: true,
			contentType: "application/json",
			url: webRoot + 'common/sysModule/queryAllForTree.do',
//			url: 'nodes.jsp',
			type: 'post'
		},
		view: {
			dblClickExpand:false,
			selectedMulti: false //如果为true,按住ctrl可以多选，false为单选 
		},
		data: {
			simpleData: {
				enable: true,
				idKey: "id",
				pIdKey: "pId",
				rootPId: 0,
				iconSkin:"icon01"
			}
		},
		callback: {
			onClick: nodeIdonClick
		}
	};
	
	var nodeIdTree = $.fn.zTree.init($("#nodeId_tree"), nodeId_setting);
	var nodeIdTreeObj = $.fn.zTree.getZTreeObj("nodeId_tree");
	function nodeIdonClick(){
		nodes = nodeIdTree.getSelectedNodes();
		var nodeIdInput = $('input[name="nodeId"]');
		// 设置控件的其他属性：vId，为真正的value
		nodeIdInput.attr("vId",nodes[0].id).val(nodes[0].name);
		hideNodeIdTree();
	};
	//下拉树相对位置，随着窗口联动
	function nodeIdTreePos(){
   		var inputObj = $('input[name="nodeId"]');
        var inputObjOffSet = $('input[name="nodeId"]').offset();
            var $treePs = $("#nodeId_commbox_tree").css({left:inputObjOffSet.left + "px", top:inputObjOffSet.top + inputObj.outerHeight() + "px",width:inputObj.outerWidth() + "px",'z-index':9999});
            return $treePs;
            }
	$('input[name="nodeId"]').click(function(){
		nodeIdTreePos().slideDown("fast");
        $(window).resize(function(){
			nodeIdTreePos();
        });
        $("body").bind("mousedown", onBodyDownNode);
	});
	function onBodyDownNode(event) {
		if (!(event.target.name == "nodeId" || event.target.id == "nodeId_commbox_tree" || $(event.target).parents("#nodeId_commbox_tree").length>0)) {
			hideNodeIdTree();
		}
	};
	function hideNodeIdTree(){
		$("#nodeId_commbox_tree").fadeOut("fast");
		$("body").unbind("mousedown", onBodyDownNode);
	};
	// 数据库，下拉树
	var dbLinkId_setting = {
		async: {
			enable: true,
			contentType: "application/json",
			url: webRoot + 'common/dbInfo/queryAllForTree.do',
//			url: 'nodes.jsp',
			type: 'post'
		},
		view: {
			dblClickExpand:false,
			selectedMulti: false //如果为true,按住ctrl可以多选，false为单选 
		},
		data: {
			simpleData: {
				enable: true,
				idKey: "id",
				pIdKey: "pId",
				rootPId: 0
			}
		},
		callback: {
			onClick: dbLinkIdonClick
		}
	};
	
	var dbLinkIdTree = $.fn.zTree.init($("#dbLinkId_tree"), dbLinkId_setting);
	var dbLinkIdTreeObj = $.fn.zTree.getZTreeObj("dbLinkId_tree");
	function dbLinkIdonClick(){
		nodes = dbLinkIdTree.getSelectedNodes();
		if(nodes[0].open){
				return;
			}
		var dbLinkIdInput = $('input[name="dbLinkId"]');
		// 设置控件的其他属性：vId，为真正的value
		dbLinkIdInput.attr("vId",nodes[0].pId).val(nodes[0].name);
		hidedbLinkIdTree();
	//	dbLinkIdInput.val(nodes[0].name);
	};
	//下拉树相对位置，随着窗口联动
	function dbLinkIdTreePos(){
   		var inputObj = $('input[name="dbLinkId"]');
        var inputObjOffSet = $('input[name="dbLinkId"]').offset();
            var $treePs = $("#dbLinkId_commbox_tree").css({left:inputObjOffSet.left + "px", top:inputObjOffSet.top + inputObj.outerHeight() + "px",width:inputObj.outerWidth() + "px",'z-index':9999});
            return $treePs;
            }
	$('input[name="dbLinkId"]').click(function(){
		dbLinkIdTreePos().slideDown("fast");
        $(window).resize(function(){
			dbLinkIdTreePos();
        });
        $("body").bind("mousedown", onBodyDownDbLink);
	});
	function onBodyDownDbLink(event) {
		if (!(event.target.name == "dbLinkId" || event.target.id == "dbLinkId_commbox_tree" || $(event.target).parents("#dbLinkId_commbox_tree").length>0)) {
			hidedbLinkIdTree();
		}
	};
	function hidedbLinkIdTree(){
		$("#dbLinkId_commbox_tree").fadeOut("fast");
		$("body").unbind("mousedown", onBodyDownDbLink);
	};
	  //数据类型
	$('input[name="sourceType"]').combobox({
				placeholder : "全部",
				dataTextField : "name",
				dataValueField : "value",
				value : "0",
				dataSource : [{
							name : "全部",
							value : "0"
						}, {
							name : "表",
							value : "1"
						}, {
							name : "文件",
							value : "2"
						}]
		});
	//执行方式
	$('input[name="execType"]').combobox({
				placeholder : "全部",
				dataTextField : "name",
				dataValueField : "value",
				value : "0",
				dataSource : [{
							name : "全部",
							value : "0"
						}, {
							name : "自动执行",
							value : "1"
						}, {
							name : "手动执行",
							value : "2"
						}]
			});
	//查询按钮
    $('#searchBtn').click(function(e) {
        var result = getPerData(1);
        $.blockUI({message : "数据载入中,请稍候..."});
//        jQuery("#user_jqGrid").jqGrid('reloadData',result);
    });

	var plan_opt = {
		datatype: "json",
		colModel:[
					{name : 'dmPlanId',label : '计划Id',width:100,sortable:false,align:'center'}, //,hidden: true
					{name : 'state',label : '状态',hidden: true}, //,hidden: true
					{name:'planName',label:'计划名称',width:200,sortable:false,align:'center'},
					{name:'execType',label:'执行方式',width:100,sortable:false,align:'center'},
					{name:'sourceData',label:'归档源数据',width:300,sortable:false,title:false,formatter:function(cellval, opts, rwdat, _act){ return formatter(cellval, opts, rwdat, _act,'sourceData')}},
					{name:'targetData',label:'归档目标数据',width:300,sortable:false,title:false,formatter:function(cellval, opts, rwdat, _act){ return formatter(cellval, opts, rwdat, _act)}},
					{name:'effDate',label:'生效日期',width:100,sortable:false,align:'center'},
					{name:'expDate',label:'失效日期',width:100,sortable:false,align:'center'},
					{name:'action',label:'操作',width:80,sortable:false,align:'center',title:false}
				],
		rowNum : 10,
		rowList : [5,10,20],
		recordtext:'第{0}~{1}条/共{2}条',
    	pgtext:'第{0}页/共{1}页',
		pginput: false,//是否显示输入框
//    	viewrecords: false,//是否显示记录描述
		pager: true,
		height:'auto',
		scrollOffset:0,
		server: true,
	    jsonReader : {
            root: "resultList",// json中代表实际模型数据的入口  
            page: "page",//当前页
            total: "totalPages",// json中代表页码总数的数据  
            records: "totalRecords",//总记录数
            repeatitems: false,// 如果设为false，则jqGrid在解析json时，会根据name来搜索对应的数据元素（即可以json中元素可以不按顺序）；而所使用的name是来自于colModel中的name设定。
            cell: "cell",
            id: "dmPlanId"
        },
	    pageData: getPerData ,//同步场景直接用getPerData,通过 jQuery("#jqGrid01").jqGrid("reloadData",getPerData(1));加载数据;异步场景用getPerData2
		forceFit:true,  //当为ture时,调整列宽度不会改变表格的宽度
		gridview : false,
		afterInsertRow: function(e,rowid, aData){  //加载每一条数据触发的事件,可修改每一行的展示,需要设置参数gridview为false
		 switch (aData.execType) {
	            case '1':
	                jQuery("#plan_jqGrid").grid('setCell',rowid,'execType','自动执行');
	            break;
	            case '2':
	                jQuery("#plan_jqGrid").grid('setCell',rowid,'execType','手动执行');
	            break;
	        };
	        var newExpDate = aData.expDate.substring(0,aData.expDate.indexOf(' '));
	        jQuery("#plan_jqGrid").grid('setCell',rowid,'expDate',newExpDate);
	        var newEffDate = aData.effDate.substring(0,aData.effDate.indexOf(' '));
	        jQuery("#plan_jqGrid").grid('setCell',rowid,'effDate',newEffDate);
			$('#plan_jqGrid').grid('setCell',rowid,'action',
			'<a href="javascript:void(0)" onclick="editRow(\''+ rowid + '\')" class="glyphicon glyphicon-edit"></a>&nbsp;&nbsp;&nbsp;&nbsp;' +
			'<a href="javascript:void(0)" onclick="delRow(\''+ rowid + '\')" class="glyphicon glyphicon-trash"></a>');
		}
	};
	$plan_grid = $("#plan_jqGrid").grid(plan_opt);
    getPerData2(1);//默认加载第一页数据
    
});
	    // 点击查看计划列表按钮的事件
		$('#addplanBtn').click(function() {
			window.open(webRoot + "planmanage/addplan/jsp/addPlan.jsp");
			return;
		});
		//重新编辑计划
		function editRow(rowid) {
			var editRow=$("#plan_jqGrid").grid("getRowData", rowid);  //获取要编辑的行数据
	        if (_.isEmpty(editRow)) 
				return;	
			var dmPlanId_editid= "dmPlanId="+editRow.dmPlanId;
			var iocpUrl = document.referrer;
			if(iocpUrl.indexOf('portal')>-1){
				iocpUrl = iocpUrl.substring(0,iocpUrl.indexOf('portal'));
			}
			var reg = new RegExp("&", "g");
			var name = editRow.planName.replace(reg, "%26");
			//	url : iocpUrl+'base/sendMessage.do?message=openUrlqq("'+webRoot+'planmanage/addplan/jsp/addPlan.jsp?'+dmPlanId_editid+'","创建执行计划",219)&channel='+parentMid,
			$.ajax({
				url : iocpUrl+'base/sendMessage.do?message=openUrlqq("'+webRoot+addplanURL+'?'+dmPlanId_editid+'%26act=edit","'+name+'",'+editRow.dmPlanId+')&channel='+parentMid,
				dataType : "jsonp",
				timeout : 3000,
				jsonpCallback:"jsonData",
				success:function(data){
				},
				error:function(){
				}
			});
		}
		//删除行数据
		function delRow(rowid) {
			var delrow = $("#plan_jqGrid").grid("getRowData", rowid); // 获取要删除的行数据
			if (_.isEmpty(delrow))
				return;
			if (delrow.state=="00X") {
				fish.toast('warn', '已经删除！');
			}else{
				fish.confirm("确定要删除吗?").result.then(function(){
					$.blockUI({message : "数据载入中,请稍候..."});
					//后台删除，将计划的状态置为00X
					$.ajax({
						url : webRoot + 'baseconfig/dmplan/delete.do',
						async : true,
						type : 'POST',
						data : {dmPlanId: delrow.dmPlanId}
					}).done(function() {
						//前台删除行数据，弹出提示框并刷新页面
						jQuery("#plan_jqGrid").jqGrid("delRowData", delrow);
						fish.toast('success', '删除成功！');
						page = $("#plan_jqGrid").jqGrid("getGridParam","page");
						recordNum = $("#plan_jqGrid").jqGrid("getGridParam","records");
						rowNum=$("#plan_jqGrid").jqGrid("getGridParam","rowNum");
						if((recordNum/rowNum)==(page-1)){
							getPerData2(1);
						}else{
							getPerData2(page);
						}
						return true;
					}).fail(function() {
						fish.toast('error', '网络连接失败');
					}).always(function() {
						$.unblockUI();
					});
				});
			}
		}

